package com.example.workflow.controller;

import com.example.workflow.dto.OrderStatusCountDto;
import com.example.workflow.dto.OrderTimeSeriesDto;
import com.example.workflow.dto.OrderTypeCountDto;
import com.example.workflow.service.UserOrderStatsService;
import com.example.workflow.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.example.workflow.pojo.LoginUser;

import java.time.LocalDate;

/**
 * 用户工单统计控制器
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserOrderStatsController {

    @Autowired
    private UserOrderStatsService userOrderStatsService;

    /**
     * 获取当前登录用户ID
     */
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 从LoginUser对象中获取用户ID
            try {
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                return loginUser.getUserInfo().getId();
            } catch (Exception e) {
                log.error("获取当前用户ID失败", e);
                return null;
            }
        }
        return null;
    }


    /**
     * 按日期范围统计工单数量，返回时序格式数据
     * 返回格式：{"time":["2023-08-01","2023-08-02",...],"count":[2,3,...]}     * 
     * @param userId 用户ID(可选)，不提供则使用当前登录用户
     * @param begin 起始日期，格式：yyyy-MM-dd
     * @param end 结束日期，格式：yyyy-MM-dd
     * @param gap 时间间隔，可选值：day/week/month
     * @return 时序格式的工单统计数据
     */
    @GetMapping("/total-count")
    public Result<OrderTimeSeriesDto> getUserOrderCount(
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "begin") String begin,
            @RequestParam(value = "end") String end,
            @RequestParam(value = "gap") String gap) {
        
        log.info("获取用户工单时序计数，userId={}, begin={}, end={}, gap={}", userId, begin, end, gap);
        
        // 如果未提供userId，则获取当前登录用户ID
        if (userId == null) {
            userId = getCurrentUserId();
            log.info("使用当前登录用户ID：{}", userId);
            if (userId == null) {
                return Result.error("未登录或无权限");
            }
        }
        
        try {
            LocalDate beginDate = LocalDate.parse(begin);
            LocalDate endDate = LocalDate.parse(end);
            
            // 验证时间间隔参数
            if (!gap.equalsIgnoreCase("day") && !gap.equalsIgnoreCase("week") && !gap.equalsIgnoreCase("month")) {
                return Result.error("时间间隔参数无效，可选值：day/week/month");
            }
            
            // 验证日期范围
            if (beginDate.isAfter(endDate)) {
                return Result.error("起始日期不能晚于结束日期");
            }
            
            OrderTimeSeriesDto stats = userOrderStatsService.countOrdersByTimeRange(userId, beginDate, endDate, gap);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("日期参数解析错误", e);
            return Result.error("日期参数格式错误，正确格式为：yyyy-MM-dd");
        }
    }
    
    /**
     * 获取用户各状态工单数量统计
     * 返回格式：{"approved":10,"completed":5,"dispatched":3,"draft":2,"operating":1,"pending_l1":1,"pending_l2":0,"processing":8,"rejected":4,"total":34}
     * 
     * @param userId 用户ID(可选)，不提供则使用当前登录用户
     * @return 各状态工单数量统计
     */
    @GetMapping("/status-count")
    public Result<OrderStatusCountDto> getUserOrderStatusCount(
            @RequestParam(value = "userId", required = false) Integer userId) {
        
        log.info("获取用户各状态工单数量统计，userId={}", userId);
        
        // 如果未提供userId，则获取当前登录用户ID
        if (userId == null) {
            userId = getCurrentUserId();
            log.info("使用当前登录用户ID：{}", userId);
            if (userId == null) {
                return Result.error("未登录或无权限");
            }
        }
        
        try {
            OrderStatusCountDto stats = userOrderStatsService.countUserOrdersByStatus(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户工单状态统计出错", e);
            return Result.error("获取工单状态统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户各类型工单数量统计
     * 返回格式：{"故障处理":10,"需求申请":5,"日常维护":3,"其它服务":2}
     * 
     * @param userId 用户ID(可选)，不提供则使用当前登录用户
     * @return 各类型工单数量统计
     */
    @GetMapping("/type-count")
    public Result<OrderTypeCountDto> getUserOrderTypeCount(
            @RequestParam(value = "userId", required = false) Integer userId) {
        
        log.info("获取用户各类型工单数量统计，userId={}", userId);
        
        // 如果未提供userId，则获取当前登录用户ID
        if (userId == null) {
            userId = getCurrentUserId();
            log.info("使用当前登录用户ID：{}", userId);
            if (userId == null) {
                return Result.error("未登录或无权限");
            }
        }
        
        try {
            OrderTypeCountDto stats = userOrderStatsService.countUserOrdersByType(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户工单类型统计出错", e);
            return Result.error("获取工单类型统计失败：" + e.getMessage());
        }
    }
} 